<?php
declare (strict_types = 1);

namespace app\validate;

use think\Validate;

class NavValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id|菜单ID' => 'require|number',
        'title|菜单标题' => 'require',
        'parent_id|父级菜单ID' => 'require|integer',
        'nav_cate_id|菜单分类ID' => 'require|number',
        'status|菜单状态' => 'require|in:1,2',
        'type|菜单类别' => 'require|in:1,2',
        'href|菜单地址' => 'requireHref',
        'sort|菜单排序' => 'require|number',
        'target|打开方式' => 'in:_blank,_self',
        'category_id|栏目ID' => 'requireIf:type,2',
        'lang|站点语言'  => 'require'
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $scene = [
        'save' => [
            'title','parent_id','nav_cate_id','status','href','sort','target','type','category_id','lang'
        ],
        'update' => [
            'id','title','parent_id','nav_cate_id','status','href','sort','target','type','category_id','lang'
        ],
        'delete' => ['id','website_id'],
        'read' => ['id','website_id'],
        'index' => ['cate_id','website_id']
    ];

    protected function requireHref($value)
    {
        if(request()->param('type') == 1){
            if(empty($value)){
                return '菜单地址不能为空';
            }
            if(preg_match('/^(?!_)[a-zA-Z0-9:&="\-_\/]/',$value)){
                return true;
            }else{
                return '链接设置错误';
            }
        }
        return true;
    }
}
